package jw.webapi.order;

import jw.model.agent.WxAgent;
import jw.model.agent.WxAgentAddress;
import jw.model.order.WxOrder;
import jw.model.order.WxOrderCommodity;
import jw.model.product.WxProductImage;
import jw.repository.agent.WxAgentAddressRepository;
import jw.repository.agent.WxAgentRepository;
import jw.repository.order.WxOrderCommodityRepository;
import jw.repository.order.WxOrderRepository;
import jw.repository.product.WxProductImageRepository;
import jw.util.HttpKit;
import jw.util.ResponseUtil;
import jw.util.WXPayUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * Created by www on 2020/1/14.
 */
@Controller
@CrossOrigin
@RequestMapping("wx/order/")
public class WxOrderWebApi {

    @Autowired
    private WxAgentRepository wxAgentRepository;

    @Autowired
    private WxAgentAddressRepository wxAgentAddressRepository;

    @Autowired
    private WxOrderCommodityRepository wxOrderCommodityRepository;

    @Autowired
    private WxOrderRepository wxOrderRepository;

    @Autowired
    private WxProductImageRepository wxProductImageRepository;

    //金薇小程序appid
    private static final String appId = "wx566d39329b5f1cf7";

    //小程序appSecret
    private static final String appSecret ="3dbba913b564f89eca98157b9accaec0";

    //商户号
    private static final String partnerId = "1490359092";

    /**
     * 下单前确认订单信息
     *
     */
    @RequestMapping("checkout")
    @ResponseBody
    public Object checkout(Integer orderId,String openId) {
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        //订单
        WxOrder wxOrder=wxOrderRepository.findOne(orderId);
        if(wxOrder==null){
            return ResponseUtil.fail(2,"商品提交有误");
        }
        //订单地址
        WxAgentAddress wxAgentAddress=wxAgentAddressRepository.findByAgentIdAndIsDefault(agent.getId(),1);
        //订单商品
        List<WxOrderCommodity> wxOrderCommodityList=wxOrderCommodityRepository.findAllByOrderId(orderId);
        Map<String,Object> result=new HashMap<>();
        result.put("checkedGoodsList",wxOrderCommodityList);
        result.put("checkedAddress",wxAgentAddress);
        result.put("wxOrder",wxOrder);

        return ResponseUtil.ok(result);
    }

    /**
     * 提交订单
     *
     */
    @RequestMapping("submit")
    @ResponseBody
    public Object submit(@RequestBody String data,HttpServletRequest request) throws Exception {
        JSONObject jsonObject=new JSONObject(data);
        if(jsonObject.isNull("orderId")||jsonObject.isNull("openId")||jsonObject.isNull("addressId")||jsonObject.isNull("message")){
            return ResponseUtil.badArgumentValue();
        }

        String openId = jsonObject.getString("openId");
        //备注留言
        String message = jsonObject.getString("message");
        //订单id
        Integer orderId = jsonObject.getInt("orderId");
        //选择地址id
        Integer addressId = jsonObject.getInt("addressId");
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        //订单
        WxOrder wxOrder=wxOrderRepository.findOne(orderId);
        if(wxOrder==null){
            return ResponseUtil.fail(2,"商品提交有误");
        }
        //订单地址
        WxAgentAddress wxAgentAddress=wxAgentAddressRepository.findOne(addressId);
        wxOrder.setRemark(message);
        wxOrder.setCreateTime(new Date());
        wxOrder.setAddress(wxAgentAddress.getAddress());
        wxOrder.setCity(wxAgentAddress.getCity());
        wxOrder.setAres(wxAgentAddress.getStreet());
        wxOrder.setStatus(0);
        wxOrder.setMobilephone(wxAgentAddress.getPhone());
        wxOrder.setReceiverName(wxAgentAddress.getReceiveName());
        wxOrder.setProvince(wxAgentAddress.getProvince());
        wxOrderRepository.save(wxOrder);

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("appid", appId);
        //商品描述
        paraMap.put("body", "kivie");
        //商户号
        paraMap.put("mch_id", partnerId);
        //随机字符串
        paraMap.put("nonce_str", WXPayUtil.create_nonce_str());
        // 通知地址
        paraMap.put("notify_url", "http://test.kivie.com/order/wxNotify");
        paraMap.put("openid", openId);
        // 商户订单号
        paraMap.put("out_trade_no", wxOrder.getOrderNumber());
        //终端IP
        paraMap.put("spbill_create_ip", WXPayUtil.getIp2(request));
        //订单金额  单位分
        paraMap.put("total_fee",wxOrder.getTotal().toString());
        //支付方式
        paraMap.put("trade_type", "JSAPI");
        System.out.println("生成的map"+paraMap);
        String sign = WXPayUtil.getSign(paraMap,appSecret);
        System.out.println("生成的签名+++"+sign);
        paraMap.put("sign", sign);

        Map<String, String> payMap = new HashMap<>();
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        String xml = WXPayUtil.mapToXml(paraMap);
        // 预付商品id
        String prepay_id;
        String msg;
        String xmlStr = HttpKit.post(url, xml);
        System.out.println("生成的xmlStr"+xmlStr);
        if (xmlStr.indexOf("SUCCESS") != -1) {
            Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
            prepay_id = map.get("prepay_id");
        }else{
            Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
            msg=map.get("return_msg");
            paraMap.put("msg",msg);
            payMap.put("resultCode","FAIL");
            return payMap;
        }
        payMap.put("appId", appId);
        payMap.put("timeStamp", WXPayUtil.create_timestamp());
        payMap.put("nonceStr", WXPayUtil.create_nonce_str());
        payMap.put("signType", "MD5");
        payMap.put("package", "prepay_id=" + prepay_id);
        String paySign = WXPayUtil.getSign(payMap, appSecret);
        payMap.put("pg", prepay_id);
        payMap.put("paySign", paySign);
        return ResponseUtil.ok(payMap);
    }

//    /**
//     * 微信小程序支付成功回调函数
//     * @param request
//     * @param response
//     * @throws Exception
//     */
//    @RequestMapping(value = "wxNotify")
//    public void wxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{
//        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
//        String line = null;
//        StringBuilder sb = new StringBuilder();
//        while((line = br.readLine()) != null){
//            sb.append(line);
//        }
//        br.close();
//        //sb为微信返回的xml
//        String notityXml = sb.toString();
//        String resXml = "";
//        System.out.println("接收到的报文：" + notityXml);
//
//        @SuppressWarnings("unchecked")
//        Map<String, String> map = PayUtil.doXMLParse(notityXml);
//
//        String returnCode = (String) map.get("return_code");
//        if("SUCCESS".equals(returnCode)){
//            //验证签名是否正确
//            Map<String, String> validParams = PayUtil.paraFilter(map);  //回调验签时需要去除sign和空值参数
//            String validStr = PayUtil.createLinkString(validParams);//把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
//            String sign = PayUtil.sign(validStr, Configure.getKey(), "utf-8").toUpperCase();//拼装生成服务器端验证的签名
//            // 因为微信回调会有八次之多,所以当第一次回调成功了,那么我们就不再执行逻辑了
//
//            //根据微信官网的介绍，此处不仅对回调的参数进行验签，还需要对返回的金额与系统订单的金额进行比对等
//            if(sign.equals(map.get("sign"))){
//                /**此处添加自己的业务逻辑代码start**/
//                // bla bla bla....
//                /**此处添加自己的业务逻辑代码end**/
//                //通知微信服务器已经支付成功
//                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
//                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
//            } else {
//                System.out.println("微信支付回调失败!签名不一致");
//            }
//        }else{
//            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
//                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
//        }
//        System.out.println(resXml);
//        System.out.println("微信支付回调数据结束");
//
//        BufferedOutputStream out = new BufferedOutputStream(
//                response.getOutputStream());
//        out.write(resXml.getBytes());
//        out.flush();
//        out.close();
//    }





    /**
     * 获取订单列表
     *
     */
    @RequestMapping("orderList")
    @ResponseBody
    public Object orderList(String openId,Integer showType,Integer page,Integer limit) {
        if (openId == null || showType == null || page == null || limit == null){
            return ResponseUtil.badArgumentValue();
        }
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        //订单
        List<WxOrder>wxOrderList;
        Integer totalPage;
        if (showType == 99){
            wxOrderList = wxOrderRepository.findByAgentIdByPage(agent.getId(),new PageRequest(page - 1, limit));
            totalPage = wxOrderRepository.findTotalPageByAgentId(agent.getId());
        } else {
            wxOrderList = wxOrderRepository.findByAgentIdAndStatus(agent.getId(),showType,new PageRequest(page - 1, limit));
            totalPage = wxOrderRepository.findTotalPageByStatus(agent.getId(),showType);
        }
        if (totalPage == null){
            totalPage = 0;
        }
        List<Map<String,Object>> orderList = new ArrayList<>();
        for (WxOrder order : wxOrderList){
            Map<String,Object> orderMap = new HashMap<>();
            orderMap.put("orderId",order.getId());
            orderMap.put("orderSn",order.getOrderNumber());
            orderMap.put("actualPrice",order.getTotal());
            orderMap.put("orderStatusText",order.getStatus() == 1 ? "待发货" : order.getStatus() == 2 ? "待收货" : order.getStatus() == 3 ? "已完成" : order.getStatus() == 0 ? "待付款" : "其他");
            List<WxOrderCommodity> commodityList = wxOrderCommodityRepository.findAllByOrderId(order.getId());
            List<Map<String,Object>> goodsList = new ArrayList<>();
            for (WxOrderCommodity commodity : commodityList){
                Map<String,Object> commodityMap = new HashMap<>();
                commodityMap.put("number",commodity.getCount());
                commodityMap.put("goodsName",commodity.getCommodityName());
                List<WxProductImage>imageList = wxProductImageRepository.findByProductIdAndIsHomePage(commodity.getCommodityId(),1);
                if (imageList.size() > 0){
                    commodityMap.put("picUrl",imageList.get(0).getUrl());
                }
                goodsList.add(commodityMap);
            }
            orderMap.put("goodsList",goodsList);
            orderList.add(orderMap);
        }
        Map<String,Object> result=new HashMap<>();
        result.put("orderList",orderList);
        result.put("showType",showType);
        result.put("page",page);
        result.put("limit",limit);
        result.put("totalPages",totalPage % limit == 0 ? totalPage / limit : totalPage / limit + 1);
        return ResponseUtil.ok(result);
    }



}
